<template>
    <div class="stock-count-page">
        <!-- 顶部筛选 -->
        <el-card class="filter-card" shadow="never">
            <div class="quick-tabs">
                <el-radio-group v-model="activeDateTab" size="large" @change="handleDateTabChange">
                    <el-radio-button v-for="item in quickDateTabs" :key="item.value" :label="item.value">
                        {{ item.label }}
                    </el-radio-button>
                </el-radio-group>
            </div>
            <el-form :model="queryForm" :inline="true" label-width="90px" class="filter-form">
                <el-form-item label="进货单号">
                    <el-input v-model="queryForm.stockinGoodsNo" placeholder="请输入进货单号" clearable />
                </el-form-item>
                <el-form-item label="供应商">
                    <el-input v-model="queryForm.supplierName" placeholder="请输入供应商名称" clearable />
                </el-form-item>
                <el-form-item label="进货负责人">
                    <el-input v-model="queryForm.stockinUser" placeholder="请输入进货负责人" clearable />
                </el-form-item>
                <el-form-item label="进货部门">
                    <el-input v-model="queryForm.stockinDepartment" placeholder="请输入进货部门" clearable />
                </el-form-item>
                <el-form-item label="进货日期">
                    <el-date-picker v-model="queryForm.dateRange" type="daterange" start-placeholder="开始日期"
                        end-placeholder="结束日期" value-format="YYYY-MM-DD" :disabled="activeDateTab !== 'custom'"
                        style="width: 260px" @change="handleCustomDateChange" />
                </el-form-item>
                <el-form-item>
                    <el-space>
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button @click="handleReset">重置</el-button>
                    </el-space>
                </el-form-item>
            </el-form>
        </el-card>

        <!-- 中部统计卡片 -->
        <el-row :gutter="16" class="stat-row">
            <el-col :span="8">
                <el-card class="stat-card amount-card" shadow="hover">
                    <div class="stat-title">
                        <el-icon>
                            <Coin />
                        </el-icon>
                        <span>进货总金额</span>
                    </div>
                    <div class="stat-value">¥{{ formatAmount(statistics.totalAmount) }}</div>
                    <div class="stat-desc">按当前筛选条件统计</div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="stat-card supplier-card" shadow="hover">
                    <div class="stat-title">
                        <el-icon>
                            <UserFilled />
                        </el-icon>
                        <span>供应商数量</span>
                    </div>
                    <div class="stat-value">{{ statistics.supplierCount }}</div>
                    <div class="stat-desc">参与供货的供应商数</div>
                </el-card>
            </el-col>
            <el-col :span="8">
                <el-card class="stat-card order-card" shadow="hover">
                    <div class="stat-title">
                        <el-icon>
                            <List />
                        </el-icon>
                        <span>进货订单数量</span>
                    </div>
                    <div class="stat-value">{{ statistics.orderCount }}</div>
                    <div class="stat-desc">合计进货单数量</div>
                </el-card>
            </el-col>
        </el-row>

        <!-- 底部表格 -->
        <el-card class="table-card" shadow="never">
            <div class="table-toolbar">
                <div class="toolbar-left">
                    <el-button type="primary" text @click="handleExport">
                        <el-icon class="toolbar-icon">
                            <Download />
                        </el-icon>
                        导出
                    </el-button>
                    <el-button text @click="fetchStockCount">
                        <el-icon class="toolbar-icon">
                            <RefreshRight />
                        </el-icon>
                        刷新
                    </el-button>
                </div>
                <div class="toolbar-right">
                    共 {{ page.listCount }} 条记录
                </div>
            </div>

            <el-scrollbar x>
                <el-table v-loading="loading" :data="tableRows" border stripe style="min-width: 1200px"
                    :span-method="tableSpanMethod" size="large">
                    <el-table-column label="序号" width="60" fixed="left" align="center">
                        <template #default="{ row }">
                            {{ getOrderIndex(row) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="stockinGoodsNo" label="进货单号" width="160" fixed="left" align="center">
                        <template #default="{ row }">
                            <el-link type="primary" @click="handleShowDetail(row)">
                                {{ row.stockinGoodsNo || '-' }}
                            </el-link>
                        </template>
                    </el-table-column>

                    <el-table-column prop="stockinGoodsDate" label="进货日期" width="140" align="center">
                        <template #default="{ row }">
                            {{ formatDate(row.stockinGoodsDate) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="stockinDepartment" label="进货部门" min-width="150" show-overflow-tooltip
                        align="center" />
                    <el-table-column prop="stockinUser" label="进货负责人" width="130" show-overflow-tooltip
                        align="center" />
                    <el-table-column prop="supplierName" label="供应商名称" min-width="160" show-overflow-tooltip
                        align="center" />
                    <el-table-column label="货品名称" min-width="160" show-overflow-tooltip align="center">
                        <template #default="{ row }">
                            {{ row.productDetail?.productName || row.productName || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="货品编号" min-width="140" show-overflow-tooltip align="center">
                        <template #default="{ row }">
                            {{ row.productDetail?.productCode || row.productCode || '-' }}
                        </template>
                    </el-table-column>
                    <el-table-column label="进货数量" width="110" align="center">
                        <template #default="{ row }">
                            {{ row.productDetail?.quantity ?? row.quantity ?? 0 }}
                        </template>
                    </el-table-column>
                    <el-table-column label="进货金额" width="130" align="center">
                        <template #default="{ row }">
                            ¥{{ formatAmount(row.productDetail?.amount ?? row.stockinGoodsAmount ?? row.amount) }}
                        </template>
                    </el-table-column>
                </el-table>
            </el-scrollbar>

            <div class="pagination-wrapper">
                <el-pagination v-model:current-page="page.pageindex" v-model:page-size="page.pagesize"
                    layout="total, sizes, prev, pager, next, jumper" :page-sizes="[5, 10, 20, 30, 50]"
                    :total="page.listCount" @current-change="handlePageChange" @size-change="handleSizeChange" />
            </div>
        </el-card>

        <!-- 详情抽屉 -->
        <el-drawer v-model="detailVisible" size="80%" :with-header="false">
            <div class="detail-wrapper" v-loading="detailLoading">
                <div class="detail-header">
                    <div class="detail-title">
                        <span class="order-no">进货单号：{{ detailBase.stockinGoodsNo || '--' }}</span>
                        <el-tag :type="getStatusTagType(detailBase.stockinGoodsStatus)">
                            {{ getStatusText(detailBase.stockinGoodsStatus) }}
                        </el-tag>
                    </div>
                    <div class="detail-sub">
                        进货日期：{{ formatDate(detailBase.stockinGoodsDate) }} ｜ 入库数量：{{ detailBase.inboundQuantity
                            ?? 0 }}
                    </div>
                </div>
                <el-card shadow="never" class="detail-card base-card">
                    <el-descriptions :column="3" border size="small">
                        <el-descriptions-item label="供应商">
                            {{ detailBase.supplierName || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="进货部门">
                            {{ detailBase.stockinDepartment || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="进货负责人">
                            {{ detailBase.stockinUser || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系人">
                            {{ detailBase.stockinContact || detailBase.contactName || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="联系电话">
                            {{ detailBase.stockinContactPhone || detailBase.contactPhone || '-' }}
                        </el-descriptions-item>
                        <el-descriptions-item label="备注">
                            {{ detailBase.remark || '-' }}
                        </el-descriptions-item>
                    </el-descriptions>
                </el-card>

                <el-card shadow="never" class="detail-card tabs-card">
                    <el-tabs v-model="detailActiveTab" type="border-card">
                        <el-tab-pane label="进货明细" name="goods">
                            <el-table :data="detailLists.goods" border stripe style="width: 100%">
                                <el-table-column type="index" width="60" label="序号" align="center" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="productCode" label="货品编号" min-width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="specificationModel" label="规格" min-width="120"
                                    show-overflow-tooltip align="center" />
                                <el-table-column prop="unitName" label="单位" width="90" align="center" />
                                <el-table-column prop="quantity" label="数量" width="110" align="center" />
                                <el-table-column prop="price" label="单价" width="110" align="center">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.price) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="amount" label="金额" width="130" align="center">
                                    <template #default="{ row }">
                                        <span class="amount-text">¥{{ formatAmount(row.amount) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="remark" label="备注" min-width="160" show-overflow-tooltip
                                    align="center" />
                            </el-table>
                            <div class="detail-summary" v-if="detailLists.goods.length">
                                <span>货品种类：{{ detailLists.goods.length }}</span>
                                <span>总数量：{{ detailTotalQuantity }}</span>
                                <span>总金额：¥{{ formatAmount(detailTotalAmount) }}</span>
                            </div>
                            <el-empty v-else description="暂无进货明细" :image-size="100" />
                        </el-tab-pane>
                        <el-tab-pane label="入库记录" name="inbound">
                            <el-table :data="detailLists.inbound" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="warehousingNo" label="入库单号" min-width="140" show-overflow-tooltip
                                    align="center">
                                    <template #default="{ row }">
                                        <el-link type="primary" :underline="false">
                                            {{ row.warehousingNo || '-' }}
                                        </el-link>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="warehousingDate" label="入库日期" width="140" align="center">
                                    <template #default="{ row }">
                                        {{ formatDate(row.warehousingDate) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="warehouseName" label="仓库名称" min-width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="warehousingProducts" label="入库货品" min-width="200"
                                    show-overflow-tooltip align="center" />
                                <el-table-column prop="warehousingQuantity" label="入库数量" width="100" align="center" />
                                <el-table-column prop="warehousingAmount" label="入库金额" width="130" align="center">
                                    <template #default="{ row }">
                                        ¥{{ formatAmount(row.warehousingAmount) }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="handler" label="经办人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="maker" label="制单人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="department" label="所在部门" width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="createdTime" label="制单时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.createdTime) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <div class="detail-summary" v-if="detailLists.inbound.length">
                                <span>入库种类：{{ inboundSummary.stockinKinds }}</span>
                                <span>入库数量：{{ inboundSummary.stockinQuantity }}</span>
                                <span>入库金额：¥{{ formatAmount(inboundSummary.totalAmount) }}</span>
                            </div>
                            <el-empty v-else description="暂无入库记录" :image-size="100" />
                        </el-tab-pane>
                        <el-tab-pane label="退货记录" name="returns">
                            <el-table :data="detailLists.returns" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="productName" label="货品名称" min-width="160" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="quantity" label="退货数量" width="120" align="center" />
                                <el-table-column prop="reason" label="退货原因" min-width="200" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="time" label="退货时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.time) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.returns.length" description="暂无退货记录" :image-size="100" />
                        </el-tab-pane>
                        <el-tab-pane label="操作记录" name="operation">
                            <el-table :data="detailLists.operations" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="operationType" label="操作类型" min-width="140" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="operator" label="操作人" width="100" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="remark" label="备注" min-width="200" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="time" label="操作时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.time) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.operations.length" description="暂无操作记录" :image-size="100" />
                        </el-tab-pane>
                        <el-tab-pane label="审核记录" name="approval">
                            <el-table :data="detailLists.approvals" border stripe style="width: 100%">
                                <el-table-column type="index" label="序号" width="60" align="center" />
                                <el-table-column prop="status" label="审核状态" width="120" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="row.status === '通过' || row.status === 1 ? 'success' : 'info'">
                                            {{ row.statusName || row.status || '—' }}
                                        </el-tag>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="approver" label="审核人" width="120" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="remark" label="意见" min-width="200" show-overflow-tooltip
                                    align="center" />
                                <el-table-column prop="time" label="审核时间" width="180" align="center">
                                    <template #default="{ row }">
                                        {{ formatDateTime(row.time) }}
                                    </template>
                                </el-table-column>
                            </el-table>
                            <el-empty v-if="!detailLists.approvals.length" description="暂无审核记录" :image-size="100" />
                        </el-tab-pane>
                    </el-tabs>
                </el-card>
            </div>
        </el-drawer>
    </div>
</template>

<script setup lang="ts">
import { computed, onMounted, reactive, ref, watch } from 'vue'
import { ElMessage } from 'element-plus'
import { Coin, UserFilled, List, RefreshRight, Download } from '@element-plus/icons-vue'
import moment from 'moment'
import myaxios from '@/http/MyAxios'

type QuickDateTab = 'today' | 'yesterday' | 'thisWeek' | 'lastWeek' | 'thisMonth' | 'lastMonth' | 'custom'

interface StockCountProduct {
    productName?: string
    productCode?: string
    specificationModel?: string
    unitName?: string
    quantity?: number
    amount?: number
    price?: number
    remark?: string
}

interface StockCountRecord {
    stockinGoodsId?: number | string
    stockinGoodsNo?: string
    stockinGoodsDate?: string
    stockinGoodsStatus?: number
    stockinDepartment?: string
    stockinUser?: string
    supplierName?: string
    inboundQuantity?: number
    stockinGoodsAmount?: number
    productName?: string
    productCode?: string
    specification?: string
    quantity?: number
    amount?: number
    stockinContact?: string
    stockinContactPhone?: string
    remark?: string
    productDetails?: StockCountProduct[]
    stockinDetails?: StockCountProduct[]
    stockinGoodsDetails?: StockCountProduct[]
    detailList?: StockCountProduct[]
    [key: string]: any
}

interface StockCountRow extends StockCountRecord {
    detailIndex: number
    detailCount: number
    orderIndex: number  // 订单序号（按订单计数，不是按行计数）
    productDetail: StockCountProduct | null
}

const quickDateTabs: Array<{ label: string, value: QuickDateTab }> = [
    { label: '今日', value: 'today' },
    { label: '昨日', value: 'yesterday' },
    { label: '本周', value: 'thisWeek' },
    { label: '上周', value: 'lastWeek' },
    { label: '本月', value: 'thisMonth' },
    { label: '上月', value: 'lastMonth' },
    { label: '自定义时间', value: 'custom' }
]

const activeDateTab = ref<QuickDateTab>('today')

const queryForm = reactive({
    stockinGoodsNo: '',
    supplierName: '',
    stockinUser: '',
    stockinDepartment: '',
    dateRange: [] as string[]
})

const statistics = reactive({
    totalAmount: 0,
    supplierCount: 0,
    orderCount: 0
})

const page = reactive({
    pageindex: 1,
    pagesize: 5,
    pageCount: 0,
    listCount: 0
})

const loading = ref(false)
const tableRows = ref<StockCountRow[]>([])
const rawRecords = ref<StockCountRecord[]>([])

const detailVisible = ref(false)
const detailLoading = ref(false)
const detailActiveTab = ref('goods')
const detailBase = reactive<Record<string, any>>({
    stockinGoodsNo: '',
    stockinGoodsDate: '',
    stockinGoodsStatus: 0,
    stockinDepartment: '',
    stockinUser: '',
    supplierName: '',
    stockinContact: '',
    stockinContactPhone: '',
    remark: '',
    inboundQuantity: 0
})

const detailLists = reactive({
    goods: [] as StockCountProduct[],
    inbound: [] as Array<Record<string, any>>,
    returns: [] as Array<Record<string, any>>,
    operations: [] as Array<Record<string, any>>,
    approvals: [] as Array<Record<string, any>>
})

const inboundSummary = reactive({
    stockinKinds: 0,
    stockinQuantity: 0,
    totalAmount: 0
})

const detailTotalQuantity = computed(() => {
    return detailLists.goods.reduce((sum, item) => sum + (item.quantity || 0), 0)
})

const detailTotalAmount = computed(() => {
    return detailLists.goods.reduce((sum, item) => sum + (item.amount || 0), 0)
})

const applyQuickRange = (tab: QuickDateTab) => {
    if (tab === 'custom') {
        if (!queryForm.dateRange || queryForm.dateRange.length !== 2) {
            queryForm.dateRange = []
        }
        return
    }
    const [start, end] = getQuickRange(tab)
    queryForm.dateRange = [start, end]
}

const getQuickRange = (tab: QuickDateTab): [string, string] => {
    const today = moment()
    switch (tab) {
        case 'today':
            return [today.clone().startOf('day').format('YYYY-MM-DD'), today.clone().endOf('day').format('YYYY-MM-DD')]
        case 'yesterday': {
            const y = today.clone().subtract(1, 'day')
            return [y.startOf('day').format('YYYY-MM-DD'), y.endOf('day').format('YYYY-MM-DD')]
        }
        case 'thisWeek':
            return [today.clone().startOf('week').format('YYYY-MM-DD'), today.clone().endOf('week').format('YYYY-MM-DD')]
        case 'lastWeek': {
            const last = today.clone().subtract(1, 'week')
            return [last.startOf('week').format('YYYY-MM-DD'), last.endOf('week').format('YYYY-MM-DD')]
        }
        case 'thisMonth':
            return [today.clone().startOf('month').format('YYYY-MM-DD'), today.clone().endOf('month').format('YYYY-MM-DD')]
        case 'lastMonth': {
            const lastMonth = today.clone().subtract(1, 'month')
            return [lastMonth.startOf('month').format('YYYY-MM-DD'), lastMonth.endOf('month').format('YYYY-MM-DD')]
        }
        default:
            return ['', '']
    }
}

const handleDateTabChange = (value: QuickDateTab) => {
    activeDateTab.value = value
    applyQuickRange(value)

    // 如果不是自定义时间，直接触发查询
    if (value !== 'custom') {
        page.pageindex = 1
        fetchStockCount()
    }
}

const handleCustomDateChange = () => {
    activeDateTab.value = 'custom'
    // 自定义日期变化时不自动查询，需要用户点击查询按钮
}

const handleQuery = () => {
    page.pageindex = 1
    fetchStockCount()
}

const handleReset = () => {
    queryForm.stockinGoodsNo = ''
    queryForm.supplierName = ''
    queryForm.stockinUser = ''
    queryForm.stockinDepartment = ''
    activeDateTab.value = 'today'
    applyQuickRange('today')
    page.pageindex = 1
    fetchStockCount()
}

const handlePageChange = (pageindex: number) => {
    // 确保使用最新的页码值（虽然 v-model 会更新，但事件参数更可靠）
    page.pageindex = pageindex
    fetchStockCount()
}

const handleSizeChange = (size: number) => {
    // 确保使用最新的每页大小值
    page.pagesize = size
    // 切换每页大小时重置到第一页
    page.pageindex = 1
    fetchStockCount()
}

const normalizeProductList = (record: StockCountRecord): StockCountProduct[] => {
    const candidateLists = [
        (record as any).details,
        record.productDetails,
        record.stockinDetails,
        record.stockinGoodsDetails,
        record.detailList,
        record.details
    ]

    for (const list of candidateLists) {
        if (Array.isArray(list) && list.length > 0) {
            return list.map(item => ({
                productName: item.productName || item.goodsName || item.product?.name || '--',
                productCode: item.productCode || item.goodsCode || item.product?.code || '--',
                specificationModel: item.specificationModel || item.specification || item.productSpecification || item.spec || item.specs || '',
                unitName: item.unitName || item.unit || item.productUnit || '',
                quantity: Number(item.quantity ?? item.stockinGoodsCount ?? item.count ?? 0),
                amount: Number(item.amount ?? item.totalAmount ?? item.stockinGoodsAmount ?? 0),
                price: Number(item.price ?? item.unitPrice ?? 0),
                remark: item.remark || ''
            }))
        }
    }

    if (record.productName || record.productCode) {
        return [{
            productName: record.productName,
            productCode: record.productCode,
            specificationModel: record.specificationModel || record.specification || '',
            unitName: record.unitName || record.unit || '',
            quantity: Number(record.stockinGoodsCount ?? record.quantity ?? 0),
            amount: Number(record.stockinGoodsAmount ?? record.amount ?? 0),
            price: Number(record.stockinGoodsAmount ?? record.amount ?? 0),
            remark: record.remark || ''
        }]
    }

    return []
}

const flattenRecords = (records: StockCountRecord[]): StockCountRow[] => {
    const rows: StockCountRow[] = []
    records.forEach((record, orderIndex) => {
        const productList = normalizeProductList(record)
        if (productList.length === 0) {
            rows.push({
                ...record,
                detailIndex: 0,
                detailCount: 1,
                orderIndex: orderIndex,  // 订单序号（从0开始）
                productDetail: null
            })
            return
        }
        productList.forEach((detail, index) => {
            rows.push({
                ...record,
                detailIndex: index,
                detailCount: productList.length,
                orderIndex: orderIndex,  // 订单序号（从0开始）
                productDetail: detail
            })
        })
    })
    return rows
}

const buildGroupedRecords = (list: StockCountRecord[]): StockCountRecord[] => {
    if (!list || list.length === 0) return []

    const map = new Map<string, StockCountRecord & { details: StockCountProduct[] }>()

    list.forEach((item, index) => {
        // 按订单号分组（后端已按订单分页，但同一订单可能有多条货品明细记录）
        const key = item.stockinGoodsNo || `unknown_${index}`

        if (!map.has(key)) {
            // 创建订单记录，保留订单信息，初始化货品明细数组
            map.set(key, {
                ...item,
                details: []
            })
        }

        const target = map.get(key)!

        // 尝试从订单记录中提取货品明细列表
        const productList = normalizeProductList(item)

        if (productList.length > 0) {
            // 如果订单记录中包含货品明细列表，直接使用
            target.details?.push(...productList)
        } else if (item.productName || item.productCode) {
            // 如果订单记录本身就是一条货品明细（扁平化结构），则添加为一条明细
            const detail: StockCountProduct = {
                productName: item.productName || '--',
                productCode: item.productCode || '--',
                specificationModel: item.specificationModel || item.specification || '',
                unitName: item.unitName || item.unit || '',
                quantity: Number(item.quantity ?? item.stockinGoodsCount ?? 0),
                amount: Number(item.amount ?? item.stockinGoodsAmount ?? 0),
                price: Number(item.price ?? item.unitPrice ?? (item.amount ?? item.stockinGoodsAmount ?? 0) / (item.quantity ?? 1)),
                remark: item.remark || ''
            }
            target.details?.push(detail)
        }
    })

    return Array.from(map.values())
}

const fetchStockCount = async () => {
    loading.value = true
    try {
        const params: Record<string, any> = {
            stockinGoodsNo: queryForm.stockinGoodsNo || undefined,
            supplierName: queryForm.supplierName || undefined,
            stockinUser: queryForm.stockinUser || undefined,
            stockinDepartment: queryForm.stockinDepartment || undefined,
            beginDate: queryForm.dateRange?.[0],
            endDate: queryForm.dateRange?.[1],
            pageindex: page.pageindex,
            pagesize: page.pagesize
        }

        const res = await myaxios.get('/api/Statis/GetStockCount', { params })
        const result = res.data?.data || {}
        const pages = result.pages || {}

        // 后端已经按订单分页，返回的是订单列表（每个订单可能包含多条货品明细）
        const orderList: StockCountRecord[] = pages.data || result.data || result.list || []

        // 按订单号分组，将同一订单的货品明细合并
        // 因为后端返回的数据可能是扁平化的（每个订单的每条货品明细一条记录）
        const groupedOrders = buildGroupedRecords(orderList)

        statistics.totalAmount = Number(result.totalAmount ?? result.statistical?.totalAmount ?? 0)
        statistics.supplierCount = Number(result.supplierCount ?? result.statistical?.supplierCount ?? 0)
        statistics.orderCount = Number(result.orderCount ?? result.statistical?.orderCount ?? groupedOrders.length)

        // 分页总数使用后端返回的订单总数（listCount 是订单数，不是货品明细数）
        page.listCount = Number(pages.listCount ?? result.listCount ?? 0)
        page.pageCount = Number(pages.pageCount ?? result.pageCount ?? Math.ceil(page.listCount / page.pagesize))

        // 保存原始订单数据（用于详情查看）
        rawRecords.value = groupedOrders
        // 将订单展开为表格行（每个订单的每条货品明细一行）
        tableRows.value = flattenRecords(groupedOrders)

        console.log('后端返回的订单列表:', orderList)
        console.log('分组后的订单记录:', rawRecords.value)
        console.log('展开后的表格行数据:', tableRows.value)
    } catch (error) {
        console.error('获取进货统计失败', error)
        ElMessage.error('获取进货统计数据失败')
    } finally {
        loading.value = false
    }
}

const detailTarget = ref<StockCountRecord | null>(null)

const handleShowDetail = async (row: StockCountRecord) => {
    console.log('显示详情，行数据:', row)
    detailTarget.value = row
    detailVisible.value = true
    detailActiveTab.value = 'goods'
    detailLoading.value = true

    // 直接使用现有数据填充详情，不依赖API调用
    resetDetailData()

    // 确保有商品数据显示
    if (detailLists.goods.length === 0) {
        // 从rawRecords中查找完整的商品列表
        const fullRecord = rawRecords.value.find(record => record.stockinGoodsNo === row.stockinGoodsNo)
        console.log('查找到的完整记录:', fullRecord)

        if (fullRecord && (fullRecord as any).details) {
            detailLists.goods = (fullRecord as any).details
            console.log('使用完整记录的details:', detailLists.goods)
        } else {
            // 如果没有details，直接从当前行创建商品信息
            detailLists.goods = [{
                productName: row.productName || row.productDetail?.productName || '-',
                productCode: row.productCode || row.productDetail?.productCode || '-',
                specificationModel: row.specificationModel || row.productDetail?.specificationModel || row.specification || '-',
                unitName: row.unitName || row.productDetail?.unitName || row.unit || '-',
                quantity: Number(row.quantity ?? row.productDetail?.quantity ?? 0),
                amount: Number(row.amount ?? row.productDetail?.amount ?? row.stockinGoodsAmount ?? 0),
                price: Number(row.price ?? row.productDetail?.price ?? 0),
                remark: row.remark || row.productDetail?.remark || '-'
            }]
            console.log('创建的商品信息:', detailLists.goods)
        }
    }

    try {
        // 加载当前单号的入库记录
        await fetchInboundRecords(row.stockinGoodsNo)
    } finally {
        detailLoading.value = false
    }
}

const resetDetailData = () => {
    detailBase.stockinGoodsNo = detailTarget.value?.stockinGoodsNo || ''
    detailBase.stockinGoodsDate = detailTarget.value?.stockinGoodsDate || ''
    detailBase.stockinGoodsStatus = detailTarget.value?.stockinGoodsStatus || 0
    detailBase.stockinDepartment = detailTarget.value?.stockinDepartment || ''
    detailBase.stockinUser = detailTarget.value?.stockinUser || ''
    detailBase.supplierName = detailTarget.value?.supplierName || ''
    detailBase.stockinContact = detailTarget.value?.stockinContact || ''
    detailBase.stockinContactPhone = detailTarget.value?.stockinContactPhone || ''
    detailBase.remark = detailTarget.value?.remark || ''
    detailBase.inboundQuantity = detailTarget.value?.inboundQuantity || 0

    // 初始化为空，让handleShowDetail来填充数据
    detailLists.goods = []
    detailLists.inbound = []
    detailLists.returns = []
    detailLists.operations = []
    detailLists.approvals = []

    inboundSummary.stockinKinds = 0
    inboundSummary.stockinQuantity = 0
    inboundSummary.totalAmount = 0
}

const normalizeRecordList = (list: any, mapper: (item: any) => any) => {
    if (Array.isArray(list)) {
        return list.map(mapper)
    }
    return []
}

const normalizeInboundRecords = (records: any): Array<Record<string, any>> => {
    if (!Array.isArray(records)) return []
    return records.map((item: any) => ({
        warehousingNo: item.warehousingNo || item.warehousingCode || item.stockinNo || item.inboundCode || item.entryOrderNo || '-',
        warehousingDate: item.warehousingDate || item.storageDate || item.warehousingTime || item.inboundDate || item.createdTime || '',
        warehouseName: item.warehouseName || item.warehousingWarehouse || item.warehouse || item.storehouseName || '-',
        warehousingProducts: item.warehousingProducts || item.productNames || item.goodsName || item.productList || '-',
        warehousingQuantity: Number(item.warehousingQuantity ?? item.warehousingNum ?? item.quantity ?? item.stockQuantity ?? item.inboundNum ?? 0),
        warehousingAmount: Number(item.warehousingAmount ?? item.warehousingMoney ?? item.amount ?? item.totalAmount ?? item.inboundAmount ?? 0),
        handler: item.handler || item.agentUserName || item.stockinUser || item.warehousingKeeper || item.operator || item.handlerName || '-',
        maker: item.maker || item.documentCreator || item.warehousingMaker || item.creator || item.makerName || '-',
        department: item.department || item.organizationName || item.warehousingDepartment || item.documentDepartment || item.orgName || '-',
        createdTime: item.createdTime || item.documentCreation || item.warehousingTime || item.documentTime || item.createdDate || '',
        remark: item.remark || item.note || '-'
    }))
}

const applyInboundRecords = (records: any[], meta?: any) => {
    detailLists.inbound = normalizeInboundRecords(records)
    const calcQuantity = detailLists.inbound.reduce((sum, cur) => sum + (cur.warehousingQuantity || 0), 0)
    const calcAmount = detailLists.inbound.reduce((sum, cur) => sum + (cur.warehousingAmount || 0), 0)

    inboundSummary.stockinKinds = Number(meta?.stockinKinds ?? detailLists.inbound.length ?? 0)
    inboundSummary.stockinQuantity = Number(meta?.stockinQuantity ?? meta?.inboundQuantity ?? calcQuantity)
    inboundSummary.totalAmount = Number(meta?.totalAmount ?? meta?.inboundAmount ?? calcAmount)

    const inboundQty = meta?.stockinQuantity ?? meta?.inboundQuantity
    if (typeof inboundQty === 'number') {
        detailBase.inboundQuantity = inboundQty
    } else {
        detailBase.inboundQuantity = calcQuantity
    }
}

const resolveRecordList = (source: any): any[] => {
    if (Array.isArray(source)) return source
    if (source && Array.isArray(source.records)) return source.records
    if (source && Array.isArray(source.list)) return source.list
    if (source && Array.isArray(source.data)) return source.data
    if (source && Array.isArray(source.items)) return source.items
    return []
}

const loadStockDetail = async (row: StockCountRecord) => {
    resetDetailData()
    detailLoading.value = true
    try {
        // 构建参数，确保至少有一个标识符
        const params: Record<string, any> = {}
        if (row.stockinGoodsId) {
            params.stockinGoodsId = row.stockinGoodsId
        }
        if (row.stockinGoodsNo) {
            params.stockinGoodsNo = row.stockinGoodsNo
        }

        // 如果没有有效的标识符，显示错误
        if (!params.stockinGoodsId && !params.stockinGoodsNo) {
            ElMessage.error('缺少进货单标识符')
            return
        }

        console.log('请求进货详情参数:', params)

        // 尝试多个可能的API路径
        let res
        try {
            console.log('尝试调用: /api/Statis/GetStockCountDetail')
            res = await myaxios.get('/api/Statis/GetStockCountDetail', { params })
        } catch (error: any) {
            console.log('第一个API调用失败:', error.response?.status, error.response?.data)
            if (error.response?.status === 404) {
                // 尝试其他可能的API路径
                try {
                    console.log('尝试调用: /api/StockinGoods/GetStockinGoodsDetail')
                    res = await myaxios.get('/api/StockinGoods/GetStockinGoodsDetail', { params })
                } catch (error2: any) {
                    console.log('第二个API调用失败:', error2.response?.status, error2.response?.data)
                    if (error2.response?.status === 404) {
                        console.log('尝试调用: /api/StockinGoods/GetStockingoodsDetail')
                        res = await myaxios.get('/api/StockinGoods/GetStockingoodsDetail', { params })
                    } else {
                        throw error2
                    }
                }
            } else {
                throw error
            }
        }
        const result = res.data?.data || {}
        const baseInfo = result.baseInfo || result.stockinInfo || result

        detailBase.stockinGoodsNo = baseInfo.stockinGoodsNo ?? detailBase.stockinGoodsNo
        detailBase.stockinGoodsDate = baseInfo.stockinGoodsDate ?? detailBase.stockinGoodsDate
        detailBase.stockinGoodsStatus = baseInfo.stockinGoodsStatus ?? detailBase.stockinGoodsStatus
        detailBase.stockinDepartment = baseInfo.stockinDepartment ?? detailBase.stockinDepartment
        detailBase.stockinUser = baseInfo.stockinUser ?? detailBase.stockinUser
        detailBase.supplierName = baseInfo.supplierName ?? detailBase.supplierName
        detailBase.stockinContact = baseInfo.stockinContact ?? baseInfo.contactName ?? detailBase.stockinContact
        detailBase.stockinContactPhone = baseInfo.stockinContactPhone ?? baseInfo.contactPhone ?? detailBase.stockinContactPhone
        detailBase.remark = baseInfo.remark ?? detailBase.remark
        detailBase.inboundQuantity = baseInfo.inboundQuantity ?? detailBase.inboundQuantity

        detailLists.goods = normalizeProductList(baseInfo).length > 0
            ? normalizeProductList(baseInfo)
            : normalizeProductList(result)

        if (!detailLists.goods.length) {
            const goodsSource = result.goodsDetails || result.stockinDetails || result.detailList || []
            detailLists.goods = normalizeRecordList(goodsSource, (item: any) => ({
                productName: item.productName || item.goodsName || '-',
                productCode: item.productCode || item.goodsCode || '-',
                specificationModel: item.specificationModel || item.specification || item.productSpecification || item.spec || item.specs || '-',
                unitName: item.unitName || item.unit || item.productUnit || '-',
                quantity: item.quantity || item.stockinGoodsCount || 0,
                amount: item.amount || item.totalAmount || item.stockinGoodsAmount || 0,
                price: item.price || item.unitPrice || 0,
                remark: item.remark || '-'
            }))
        }

        detailLists.inbound = normalizeRecordList(result.inboundRecords || result.inboundList, (item: any) => ({
            warehouseName: item.warehouseName || item.storageName,
            productName: item.productName,
            quantity: item.quantity,
            operator: item.operator || item.userName,
            time: item.inboundTime || item.time
        }))

        detailLists.returns = normalizeRecordList(result.returnRecords || result.returnList, (item: any) => ({
            productName: item.productName,
            quantity: item.quantity,
            reason: item.reason || item.remark,
            operator: item.operator || item.userName,
            time: item.returnTime || item.time
        }))

        detailLists.operations = normalizeRecordList(result.operationRecords || result.operationList, (item: any) => ({
            operationType: item.operationType || item.typeName,
            operator: item.operator || item.userName,
            remark: item.remark,
            time: item.operationTime || item.time
        }))

        detailLists.approvals = normalizeRecordList(result.approvalRecords || result.approvalList, (item: any) => ({
            status: item.status ?? item.approvalStatus,
            statusName: item.statusName || item.approvalStatusName,
            approver: item.approver || item.userName,
            remark: item.remark,
            time: item.approvalTime || item.time
        }))
    } catch (error: any) {
        console.error('获取进货详情失败，使用现有数据作为备用方案', error)

        // 使用现有数据作为备用方案
        console.log('使用现有数据填充详情:', row)

        // 基本信息已经在resetDetailData中设置了，这里补充一些可能缺失的字段
        if (row.stockinContact || row.contactName) {
            detailBase.stockinContact = row.stockinContact || row.contactName
        }
        if (row.stockinContactPhone || row.contactPhone) {
            detailBase.stockinContactPhone = row.stockinContactPhone || row.contactPhone
        }

        // 如果当前行有商品详情数据，使用它
        if (row.productDetail || row.productName || row.productCode) {
            const productData = row.productDetail || row
            detailLists.goods = [{
                productName: productData.productName || row.productName || '-',
                productCode: productData.productCode || row.productCode || '-',
                specificationModel: productData.specificationModel || row.specificationModel || productData.specification || row.specification || '-',
                unitName: productData.unitName || row.unitName || productData.unit || row.unit || '-',
                quantity: Number(productData.quantity ?? row.quantity ?? 0),
                amount: Number(productData.amount ?? row.amount ?? row.stockinGoodsAmount ?? 0),
                price: Number(productData.price ?? row.price ?? 0),
                remark: productData.remark || row.remark || '-'
            }]
        }

        // 查找同一进货单号的所有商品
        const sameOrderRows = rawRecords.value.find(record => record.stockinGoodsNo === row.stockinGoodsNo)
        if (sameOrderRows && (sameOrderRows as any).details) {
            detailLists.goods = (sameOrderRows as any).details
        }

        ElMessage.warning('详情接口暂不可用，显示基本信息')
    } finally {
        detailLoading.value = false
    }
}

const fetchInboundRecords = async (stockinGoodsNo?: string) => {
    detailLists.inbound = []
    inboundSummary.stockinKinds = 0
    inboundSummary.stockinQuantity = 0
    inboundSummary.totalAmount = 0

    if (!stockinGoodsNo) {
        detailBase.inboundQuantity = 0
        return
    }

    const requestQueue = [
        {
            url: '/api/Statis/GetWareHousingRecords',
            params: { stockinGoodsNo }
        },
        {
            url: '/api/StockWareHous/GetWareHousingRecords',
            params: { stockinGoodsNo }
        },
        {
            url: '/api/Statis/GetStockWarehousingRecords',
            params: { stockinGoodsNo }
        }
    ]

    let lastError: unknown = null
    for (const request of requestQueue) {
        try {
            const res = await myaxios.get(request.url, { params: request.params })
            const payload = res.data?.data ?? res.data ?? {}
            const records = resolveRecordList(payload)

            if (records && records.length) {
                applyInboundRecords(records, payload)
                return
            }

            if (Array.isArray(payload) && payload.length === 0) {
                return
            }
            if (Array.isArray(payload.records) && payload.records.length === 0) {
                // 已成功请求但无数据，保持空数据但不再尝试后续接口
                return
            }
            if (Array.isArray(payload.list) && payload.list.length === 0) {
                return
            }
        } catch (error) {
            lastError = error
        }
    }

    detailBase.inboundQuantity = 0
    if (lastError) {
        console.error('获取入库记录失败', lastError)
        ElMessage.warning('入库记录获取失败，展示基本信息')
    }
}

const handleExport = async () => {
    try {
        const params = {
            stockinGoodsNo: queryForm.stockinGoodsNo || undefined,
            supplierName: queryForm.supplierName || undefined,
            stockinUser: queryForm.stockinUser || undefined,
            stockinDepartment: queryForm.stockinDepartment || undefined,
            beginDate: queryForm.dateRange?.[0],
            endDate: queryForm.dateRange?.[1]
        }
        const res = await myaxios.get('/api/Statis/ExportStockCount', {
            params,
            responseType: 'blob'
        })
        const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' })
        const url = URL.createObjectURL(blob)
        const a = document.createElement('a')
        a.href = url
        a.download = `进货统计_${moment().format('YYYYMMDDHHmmss')}.xlsx`
        document.body.appendChild(a)
        a.click()
        document.body.removeChild(a)
        URL.revokeObjectURL(url)
        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败', error)
        ElMessage.error('导出失败，请稍后重试')
    }
}

// 计算订单序号（考虑分页）
const getOrderIndex = (row: StockCountRow) => {
    // 序号 = (当前页码 - 1) * 每页大小 + 订单序号 + 1
    return (page.pageindex - 1) * page.pagesize + row.orderIndex + 1
}

const spanColumns = ['stockinGoodsNo', 'stockinGoodsDate', 'stockinDepartment', 'stockinUser', 'supplierName', 'stockinGoodsStatus', 'inboundQuantity']

const tableSpanMethod = ({ row, column }: { row: StockCountRow, column: any }) => {
    // 序号列特殊处理（自定义序号列，通过 label 判断）
    if (column.label === '序号') {
        if (row.detailIndex === 0) {
            return { rowspan: row.detailCount, colspan: 1 }
        }
        return { rowspan: 0, colspan: 0 }
    }

    if (spanColumns.includes(column.property)) {
        if (row.detailIndex === 0) {
            return { rowspan: row.detailCount, colspan: 1 }
        }
        return { rowspan: 0, colspan: 0 }
    }
    return { rowspan: 1, colspan: 1 }
}

const formatAmount = (value?: number | string) => {
    const num = Number(value || 0)
    return num.toFixed(2)
}

const formatDate = (date?: string) => {
    if (!date) return '-'
    return moment(date).format('YYYY-MM-DD')
}

const formatDateTime = (date?: string) => {
    if (!date) return '-'
    return moment(date).format('YYYY-MM-DD HH:mm:ss')
}

const getStatusText = (status?: number) => {
    switch (status) {
        case 0:
            return '草稿'
        case 1:
            return '待审核'
        case 2:
            return '部分入库'
        case 3:
            return '已入库'
        case 4:
            return '已关闭'
        case 5:
            return '已作废'
        default:
            return '——'
    }
}

const getStatusTagType = (status?: number) => {
    switch (status) {
        case 3:
            return 'success'
        case 1:
        case 2:
            return 'warning'
        case 4:
        case 5:
            return 'danger'
        default:
            return 'info'
    }
}

// watch 逻辑已移至 handleDateTabChange 中处理

onMounted(() => {
    applyQuickRange(activeDateTab.value)
    fetchStockCount()
})
</script>

<style scoped>
.stock-count-page {
    padding: 20px;
    background: #f5f7fa;
    min-height: 100vh;
}

.filter-card {
    margin-bottom: 16px;
}

.filter-form {
    margin-top: 16px;
}

.quick-tabs {
    display: flex;
    justify-content: space-between;
}

.stat-row {
    margin-bottom: 16px;
}

.stat-card {
    border-radius: 12px;
    background: #fff;
    transition: all 0.3s ease;
}

.stat-card .stat-title {
    display: flex;
    align-items: center;
    gap: 6px;
    font-size: 14px;
    color: #86909c;
}

.stat-card .stat-value {
    font-size: 32px;
    font-weight: 600;
    margin: 8px 0;
}

.stat-card .stat-desc {
    font-size: 12px;
    color: #c0c4cc;
}

.amount-card .stat-value {
    color: #1677ff;
}

.supplier-card .stat-value {
    color: #34c759;
}

.order-card .stat-value {
    color: #fa6400;
}

.table-card {
    border-radius: 12px;
}

.table-toolbar {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 12px;
}

.toolbar-left .el-button {
    margin-right: 8px;
}

.toolbar-icon {
    margin-right: 4px;
}

.pagination-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 16px;
}

.detail-wrapper {
    padding: 12px 24px 24px;
}

.detail-header {
    margin-bottom: 16px;
}

.detail-title {
    display: flex;
    align-items: center;
    gap: 12px;
    font-size: 18px;
    font-weight: 600;
}

.detail-sub {
    margin-top: 8px;
    color: #86909c;
}

.detail-card {
    margin-bottom: 16px;
    border-radius: 12px;
}

.detail-summary {
    margin-top: 12px;
    display: flex;
    gap: 24px;
    font-size: 14px;
    color: #606266;
}

.amount-text {
    color: #ff5722;
    font-weight: 600;
}

@media (max-width: 1200px) {
    .stat-row {
        display: block;
    }

    .stat-row .el-col {
        width: 100%;
        margin-bottom: 12px;
    }
}
</style>
